package com.tbsoft.ehr.login.dao;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.tbsoft.ehr.dao.BaseDaoImpl;
import com.tbsoft.ehr.login.MenuInfo;
import com.tbsoft.ehr.login.RoleInfo;
import com.tbsoft.ehr.login.UserInfo;

public class LoginDaoImpl extends BaseDaoImpl<UserInfo>
implements LoginDao
{

	@Override
	public UserInfo getUserInfoById(final String userId,final String authPassword) {
		 return	(UserInfo) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
					SQLQuery query  =arg0.createSQLQuery("select USER_NAME,USER_PASSWORD,password(?) as authPassword from EHR_USER where USER_ID=? and STATUS='A'");
					query.setString(0, authPassword);
					query.setString(1, userId);
					Object[] objs=(Object[]) query.uniqueResult();
					if(objs == null){
						return null;
					}
					UserInfo tmpUser = new UserInfo();
					tmpUser.setUserId(userId);
					tmpUser.setUserName(String.valueOf(objs[0]));
					tmpUser.setPassword(String.valueOf(objs[1]));
					tmpUser.setAuthPassword(String.valueOf(objs[2]));
					return tmpUser;
				}
			});
	}
	
	@Override
	public UserInfo getUserInfoById(String userId) {
		UserInfo userInfo=(UserInfo) getHibernateTemplate().get(UserInfo.class, userId);
		Set<RoleInfo> tmpRoleSet = new HashSet<RoleInfo>();
		Set<MenuInfo> tmpMenuSet = new HashSet<MenuInfo>();
		Set<MenuInfo> rootMenuSet = new HashSet<MenuInfo>();
		for(RoleInfo ri:userInfo.getRoleSet()){
			if("D".equals(ri.getStatus())){
				continue;
			}
			tmpRoleSet.add(ri);
			for(MenuInfo mi : ri.getMenuSet()){
				if(!"D".equals(mi.getStatus())){
					tmpMenuSet.add(mi);
				}
			}
		}
		StringBuilder sbf = new StringBuilder();
		for(MenuInfo mi:tmpMenuSet){
			if(2==mi.getLevel()&& mi.getParentMenuId() != null && !mi.getParentMenuId().isEmpty()){
				sbf.append("'").append(mi.getParentMenuId()).append("',");
			}
		}
		if(sbf.length()>0){		
			final String sql = "from MenuInfo mi where mi.menuId in ("+sbf.toString().substring(0,sbf.length()-1)+") and mi.status != 'D'";
			@SuppressWarnings("unchecked")
			List<MenuInfo> parentMenuList= (List<MenuInfo>) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
					return arg0.createQuery(sql).list();
				}
			});
			rootMenuSet.addAll(parentMenuList);
		}
		for(MenuInfo rmi:rootMenuSet){
			for(MenuInfo cmi:tmpMenuSet){
				if(cmi.getParentMenuId().equals(rmi.getMenuId())){
					rmi.getChildMenuInfo().add(cmi);
				}
			}
		}
		//对菜单排序
		userInfo.setRoleSet(tmpRoleSet);
		userInfo.setMenuSet(rootMenuSet);
		return userInfo;
	}
	
}
